package com.aaa.marketresearch.android.app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import com.aaa.marketresearch.android.data.UserInfo;
import com.aaa.marketresearch.android.data.domain.BillContent;
import com.aaa.marketresearch.android.data.domain.Offer;
import com.aaa.marketresearch.android.service.HttpClient;
import com.aaa.marketresearch.android.util.SimpleLog;
import com.aaa.marketresearch.android.util.connector.IDataTextResponse;
import com.aaa.marketresearch.android.widget.NavigationMenu;
import com.aaa.marketresearch.android.widget.OfferAdapter;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Nail
 */
public class OfferScreen extends Activity {

    private ListView listView;

    private List<Offer> offers = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offer_screen);
        this.listView = (ListView) findViewById(R.id.offerList);

        EditText editText = (EditText) findViewById(R.id.offerField);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String partName = s.toString();
                OfferScreen.this.reloadOffer(partName);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        EditText editText = (EditText) findViewById(R.id.offerField);
        String partName = editText.getText().toString();

        this.reloadOffer(partName);

        NavigationMenu navigationMenu = (NavigationMenu) findViewById(R.id.navigationMenu);
        navigationMenu.reload();
        navigationMenu.hideOffer();
    }

    public void familyMemberPressed(View view) {
        Intent intent = new Intent(this, FamilyScreen.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        this.startActivity(intent);
    }

    public void marketPressed(View view) {
        Intent intent = new Intent(this, MarketScreen.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        this.startActivity(intent);
    }

    public void offerPressed(View view) {
        Intent intent = new Intent(this, OfferScreen.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        this.startActivity(intent);
    }

    public void billPressed(View view) {
        Intent intent = new Intent(this, BillScreen.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        this.startActivity(intent);
    }

    private void reloadOffer(String partName) {

        if (partName != null && partName.length() > 2) {

            HttpClient httpClient = new HttpClient(this.getApplicationContext());
            httpClient.getOffers(new IDataTextResponse() {
                @Override
                public void onTextResponse(String text) {
                    OfferScreen.this.offersLoaded(text);
                }

                @Override
                public void onError() {
                    SimpleLog.info("addOfferButton onError");
                }
            }, partName.toLowerCase());
        } else {
            offersLoaded("[]");
        }
    }

    public void scanBarcodeButton(View view) {
        SimpleLog.info("scanBarcodeButton");
        Intent intent = IntentIntegrator.createScanIntent(this);
        IntentIntegrator.setCaptureLayout(intent, R.layout.scan_barcode_view);
        IntentIntegrator.startIntent(intent, this);
    }

    public void addOfferButton(View view) {
        SimpleLog.info("addOfferButton");

        UserInfo userInfo = UserInfo.getInstance();
        Offer offer = new Offer();

        BillContent billContent = userInfo.getCurrentBillContent();
        billContent.setOffer(offer);

        Intent intent = new Intent(this, OfferEditScreen.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        this.startActivity(intent);
    }

    private void offersLoaded(String json) {
        if (json != null) {
            JSONParser parser = new JSONParser();
            JSONArray data = null;
            try {
                data = (JSONArray) parser.parse(json);
            } catch (ParseException e) {
                SimpleLog.error(e.toString());
            }
            Object obj = null;

            int n = data.size();
            if (n >= 0) {
                this.offers = new ArrayList<>(n);
                for (int i = 0; i < n; i++) {
                    JSONObject jObj = (JSONObject) data.get(i);
                    Offer offer = new Offer();
                    offer.setWithJSONObject(jObj);
                    this.offers.add(offer);
                }

                OfferAdapter adapter = new OfferAdapter(this, this.offers);

                this.listView.setAdapter(adapter);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            final String barcode = result.getContents();
            if (barcode != null) {
                SimpleLog.info(barcode);
                HttpClient httpClient = new HttpClient(this.getApplicationContext());
                httpClient.getOffers(new IDataTextResponse() {
                    @Override
                    public void onTextResponse(String text) {
                        if (text != null && text.length() > 4) {
                            OfferScreen.this.offerLoaded(text);
                        } else {
                            OfferScreen.this.offerCreate(barcode);
                        }
                    }

                    @Override
                    public void onError() {
                        SimpleLog.info("load Offer by barcode onError");
                    }
                }, barcode);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void offerLoaded(String json) {
        if (json != null) {
            JSONParser parser = new JSONParser();
            JSONObject jObj = null;
            try {
                jObj = (JSONObject) parser.parse(json);
            } catch (ParseException e) {
                SimpleLog.error(e.toString());
            }
            Offer offer = new Offer();
            offer.setWithJSONObject(jObj);

            UserInfo userInfo = UserInfo.getInstance();
            BillContent billContent = userInfo.getCurrentBillContent();
            billContent.setOffer(offer);
        }
    }

    private void offerCreate(String barcodeString) {
        Long barcode = Long.parseLong(barcodeString);

        Offer offer = new Offer();
        offer.setBarcode(barcode);

        UserInfo userInfo = UserInfo.getInstance();
        BillContent billContent = userInfo.getCurrentBillContent();
        billContent.setOffer(offer);

        Intent intent = new Intent(this, OfferEditScreen.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        this.startActivity(intent);

    }
}
